package com.ciwong.epaper.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.CWLog;

import static com.ciwong.epaper.service.UploadServiceHelper.FILE_FLAGE_UPLOADED_ANSWER_CIONG;
import static com.ciwong.epaper.service.UploadServiceHelper.FILE_FLAGE_UPLOADED_DIR;

public class UploadeFailService extends Service {
    private final String TAG = "UploadeFailService";

    public static void startService() {
        try {
            if (EApplication.getInstance() == null)
                return;
            Context applicationContext = EApplication.getInstance().getApplicationContext();
            if (applicationContext == null)
                return;
            applicationContext.startService(new Intent(applicationContext, UploadeFailService.class));
        } catch (Exception e) {
            e.printStackTrace();
            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_SERVICE_UPLOAD_AUDIO, "自己捕获异常：" + e.getMessage(), "开启服务异常");
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init() {
        registerReceiver();
        registerALiYunManagerListener();
        Log.d(TAG, "init：服务启动了");
        UploadServiceHelper.traversalDeleteUpLoadedMP3s(ESystem.getAnswersNUploadPathCreate());//遍历删除上传完成并且是提交过作业的文件
        UploadServiceHelper.checkDirIsEmpty(ESystem.getAnswersNUploadPathCreate());//遍历删除空文件
        UploadServiceHelper.checkDirIsOnlyContainUploadedFlag(ESystem.getAnswersNUploadPathCreate());//遍历删除空文件
        UploadServiceHelper.traversalUpLoadUnUPMP3s();//遍历删除上传完成并且是提交过作业的文件
        UploadServiceHelper.renameDirContainUploadedFlag(ESystem.getAnswersNUploadPathCreate());//遍历重命名上传完成并且是提交过作业的文件
    }

    private void registerALiYunManagerListener() {
        ALiYunManager.getInstance().registerListener(aLiYunListener);
    }

    /**
     * @hide
     */
    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        // TODO: 2018/10/23 不同广播
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//网络
        intentFilter.addAction(IntentFlag.INTENT_FLAG_APP_ON_FRONT);//后台到前台
        intentFilter.addAction(IntentFlag.INTENT_FLAG_COMPLATE_ONE_HOMEWORK);//完成作业广播
        intentFilter.addAction(IntentFlag.INTENT_FLAG_HOMEWORK_VIEW_DETAILS);//查看作业详情广播
        registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
        ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
    }

    ALiYunManager.ALiYunListener aLiYunListener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {
        }

        @Override
        public void onSuccess(Object tag, String url) {
            CWLog.d(TAG, "上传成功了： " + tag.toString() + "\n" + url + "\n" + Thread.currentThread());
            if (tag.toString().contains("/newspaper/answers/")) {
                String reNameTag = FileUtil.reNameFile(tag.toString());//删除上传完成
                if (reNameTag.contains(FILE_FLAGE_UPLOADED_DIR))//删除提交过作业 并上传成功的音频
                    FileUtil.delete(reNameTag);
            }
        }


        @Override
        public void onFailure(Object tag, int errorCode) {
            CWLog.d(TAG, "上传失败了： " + tag.toString() + "\n" + Thread.currentThread() + "\n" + errorCode);
        }
    };


    //创建内部官博接收器
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            handleReceiver(context, intent);
        }
    };

    // TODO: 2018/10/23 找个合适的删除空文件夹的机会
    private void handleReceiver(Context context, Intent intent) {
        Log.d(TAG, "接到广播：" + intent.getAction());
        try {
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {//网络变化
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = connectivityManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    String name = info.getTypeName();
                    Log.d("mark", "当前网络名称：" + name);
                    UploadServiceHelper.traversalUpLoadUnUPMP3s();//遍历上传文件
                } else {
                    Log.d("mark", "没有可用网络");
                }
            } else if (IntentFlag.INTENT_FLAG_APP_ON_FRONT.equals(intent.getAction())) {//app启动或者后台到前台
                UploadServiceHelper.traversalUpLoadUnUPMP3s();//遍历上传文件
            } else if (IntentFlag.INTENT_FLAG_COMPLATE_ONE_HOMEWORK.equals(intent.getAction())) {//完成作业广播
                String answersUuidPath = "";
                String uuid = "";
                int typeMp3 = -1;
                long startWorkTime;
                if (intent == null) {//当广播接到信息为空
                    UploadServiceHelper.traversalUpLoadUnUPMP3s();//遍历上传文件
                } else {
                    uuid = intent.getStringExtra(IntentFlag.INTENT_FLAG_UUID);
                    typeMp3 = intent.getIntExtra(IntentFlag.INTENT_FLAG_MP3_TYPE, -1);
                    startWorkTime = intent.getLongExtra(IntentFlag.INTENT_FLAG_WORK_START_TIME,0);
                    if (TextUtils.isEmpty(uuid) || typeMp3 == -1) {//当广播接不到有用信息
                        UploadServiceHelper.traversalUpLoadUnUPMP3s();//遍历上传文件
                    } else {
                        if (typeMp3 == IntentFlag.INTENT_FLAG_MP3_TYPE_WORD) {
                            answersUuidPath = ESystem.getAnswersUserIdTypeUuidPathWord(uuid);
                        } else if (typeMp3 == IntentFlag.INTENT_FLAG_MP3_TYPE_SENTENCE) {
                            answersUuidPath = ESystem.getAnswersUserIdTypeUuidPathSentence(uuid);
                        }
                        try {
                            System.out.println("lzh前==>>:  " + "为完成作业标记");
                            FileUtil.makeFlagUploadedHomework(answersUuidPath, FILE_FLAGE_UPLOADED_ANSWER_CIONG);
                            FileUtil.reNameDir(answersUuidPath, FileUtil.getReNameDirPath(answersUuidPath));//重命名提交完成的音频
                            System.out.println("lzh后==>>:  " + "为完成作业标记");
                        } catch (Exception e) {
                            System.out.println("lzhException==>>: " + e.getMessage());
                            FileUtil.makeFlagUploadedHomework(answersUuidPath, FILE_FLAGE_UPLOADED_ANSWER_CIONG);
                        }
                        UploadServiceHelper.upLoadDirMP3s(FileUtil.getReNameDirPath(answersUuidPath),startWorkTime);//删除上传完成的音频
                    }
                    /**
                     * 兼容老版本（升级时有做了部分作业未提交），遍历老的uuid文件
                     */
                    //                uuid="";
                    //                System.out.println("lzh==>uuid："+uuid);
                    UploadServiceHelper.uploadOldVersionFile(uuid,startWorkTime);
                }
            } else if (IntentFlag.INTENT_FLAG_HOMEWORK_VIEW_DETAILS.equals(intent.getAction())) {//查看作业详情广播
                UploadServiceHelper.traversalUpLoadUnUPMP3s();//遍历上传文件
            }
        } catch (Exception e) {
            e.printStackTrace();
            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_SERVICE_UPLOAD_AUDIO, "自己捕获异常：" + e.getMessage(), "接到广播处理上传音频：" + intent.getAction());
        }
    }
}
